import fs from 'fs';
import lodash from 'lodash';
import { createRequire } from 'module';
import path from 'path';
import { build } from 'vite';
import base from './base.js';

const require = createRequire(import.meta.url);

export default function getConfig(params = {}) {
  const buildStandAlone = process.argv.at(-1) === 'standalone';
  let { outDir, componentPath } = params ?? {};
  if (buildStandAlone) {
    outDir += '-standalone';
  }
  const componentPathBasic = `${componentPath}/basic`;
  const componentPathBussiness = `${componentPath}/bussiness`;
  const ext = ['tsx', 'ts', 'jsx', 'js', 'vue'];

  const entry = {
    // [buildStandAlone ? 'index' : 'full']: `${componentPath}/index.js`,
    index: `${componentPath}/index.js`,
    lang: `${componentPath}/lang/index.js`,
  };

  if (buildStandAlone) {
    [componentPathBasic, componentPathBussiness].forEach(p => {
      fs.readdirSync(p).forEach(k => {
        if (['.DS_Store'].includes(k)) {
          return;
        }
        const v = `${p}/${k}`;
        const s = fs.statSync(v);

        if (s.isFile()) {
          entry[k.replace(path.extname(k), '')] = v;
        }

        if (s.isDirectory()) {
          let b = ext.some(extname => {
            return fs.existsSync(`${v}/index.${extname}`);
          });

          if (b) {
            k = lodash.upperFirst(lodash.camelCase(k));
            entry[k] = v;
          } else {
            fs.readdirSync(v)
              .filter(k_ => {
                return ext.some(extname => {
                  return k_.endsWith(`.${extname}`);
                });
              })
              .forEach(k_ => {
                let key = `${k}/${k_.replace(path.extname(k_), '')}`;
                entry[key] = `${v}/${k_}`;
              });
          }
        } else {
        }
      });
    });
  }

  let o = {
    publicDir: false,
    define: {},
    plugins: [
      {
        name: 'vite-lib-plugin',
        apply: 'build',
        config(v, o) {},
        configResolved(v) {
          return v;
        },
        options(v) {
          return v;
        },
        buildStart(v) {
          return v;
        },
        buildEnd(v) {
          return v;
        },
        closeBundle() {
          const a = [
            'name',
            'version',
            'peerDependencies',
            'publishConfig',
            'main',
            'module',
            'types',
          ].map(k => [
            k,
            require(path.resolve(process.cwd(), 'package.json'))[k],
          ]);

          // let vp = require('t/package.json');
          let o = lodash.merge(Object.fromEntries(a), {
            // peerDependencies: { ...vp.dependencies, ...vp.peerDependencies },
          });

          fs.writeFileSync(
            path.resolve(outDir ?? '', 'package.json'),
            JSON.stringify(o),
            'utf8',
          );

          // fs.mkdirSync(`${outDir}/lang`, { recursive: true });
          // child_process.execSync(
          //   `cp -r node_modules/@teld/q-components/lang/* ${outDir}/lang`,
          // );
        },
        // resolveId(id) {
        // },
        // load(id) {
        // },
        // transform(src, id) {},
      },
    ].filter(Boolean),
    build: {
      outDir: outDir,
      emptyOutDir: true,
      rollupOptions: {
        output: {
          chunkFileNames(v) {
            return '[name].js';
          },
        },
        external: ['vue'],
      },
      lib: {
        formats: [
          // 'cjs',
          // 'amd',
          'es',
          // 'iife',
        ].filter(Boolean),
        entry: entry,
      },
    },
  };

  return o;
}

let o = await base(
  { command: 'build', mode: 'production', ssrBuild: false },
  getConfig({
    componentPath: 'components',
    outDir: 'dist/esm',
  }),
);

await build(o);
